<template>
  <div class="search">
    <NavBar></NavBar>

    <div class='searchInput'>
      <div class="ipt">
        <i class="iconFont"></i>
        <input @focus="focusing" @keyup="getSearchValue" @keydown.enter="searching" v-model="keyWords" ref="searchInput" class="input-test" type="text" placeholder="搜索歌曲、歌手、专辑">
        <i v-show="keyWords" class="close_btn" @click="clearInput"></i>
      </div>
    </div>

    <div class="history_container" ref="dot" v-show="!keyWords&&isopen">
      <TitleText>热门搜索</TitleText>
      <div class="history_list">
        <!--默认关键词  -->
        <div v-for="item in historyList" :key="item.id" @click="historyClcik(item.first)">
          <!-- <div v-show="historyList.length==0">无相关结果！</div> -->
          <HistoryRadiu>{{item.first}}</HistoryRadiu>
        </div>
      </div>
      <!-- 历史记录 -->
      <div class="session_box">
        <div v-for="(item,index) in session" :key="index">
          <SearchList :searchList='item'>
            <template #before>
              <i class="icon1"></i>
            </template>
            <template #after>
              <i class="icon2" @click="delSession(item.name)"></i>
            </template>
          </SearchList>
        </div>

      </div>
    </div>

    <!-- 关键词搜索列表 -->
    <div v-show="(keyWords&&isUpdate&&isopen )">
      <div class="SearchListTitle">
        搜索"{{keyWords}}"
      </div>
      <div class="sl" @click="jumpSongs1(item.id)" v-for="(item,index) in searchList" :key="index">
        <SearchList :searchList='item'>
          <template #before>
            <i class="iconFont2"></i>
          </template>
        </SearchList>
      </div>
      <!-- 搜索触底 -->
      <div v-show="addPage2.length>0" ref="more2" class="more">{{page2>=searchList.length/pageSize2?"我是有底线的(●'◡'●)":"点击加载更多"}}</div>

    </div>
    <!-- 点击后搜索 -->
    <div style="padding:0 30px;">
      <div @click="jumpSongs(item.id)" class="music" style="paddingLeft:10px" v-show="isopen2" v-for="(item,index) in smallkeywordsList" :key="index">
        <MusicList :musicList="item" :keywords="keyWords"></MusicList>
      </div>
      <div v-show="addPage.length>0" ref="more" class="more">{{page>=keywordsList.length/pageSize?"我是有底线的(●'◡'●)":"点击加载更多"}}</div>

      <!-- <div v-show="addPage.length>0&&isopen2" class="more" @click="loadMore">{{page>=keywordsList.length/pageSize?"我是有底线的(●'◡'●)":"点击加载更多"}}</div> -->
    </div>
    <!-- <div class="scrollBar">
      <ScrollBottom></ScrollBottom>
    </div>
    <div class="end">
      <LoadingEnd></LoadingEnd>
    </div> -->
    <div class="clearHistory" @click="clearHistory">清空历史记录</div>
  </div>
</template>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
<script>
import TitleText from '@/components/TitleText';
import HistoryRadiu from '@/components/HistoryRadiu';
import SearchListTitle from '@/components/SearchListTitle';
import SearchList from '@/components/SearchList';
import MusicList from '@/components/MusicList';
import ScrollBottom from '@/components/ScrollBottom';
import LoadingEnd from '@/components/LoadingEnd';
import _ from 'lodash';

export default {
  name: 'Search',
  components: {
    TitleText,
    HistoryRadiu,
    SearchListTitle,
    SearchList,
    MusicList,
    ScrollBottom,
    LoadingEnd,
    SearchListTitle
  },
  data() {
    return {
      isipt: false,
      historyList: [],
      inputValue: '',
      searchList: [],
      keywordsList: [],
      page: 1,
      pageSize: 10,
      page2: 1,
      pageSize2: 10,
      isopen: true,
      isopen2: false,
      keyWords: '',
      smallkeywordsList: [],
      session: [],
      isUpdate: false
    };
  },
  created() {
    this.session = JSON.parse(sessionStorage.getItem('nameArray'));
    this.getSearchHistory();
    this.getSearchValue();
  },
  updated() {
    this.inputValue = this.$store.state.searchValue;
  },
  watch: {
    inputValue() {
      this.getSearchValue();
    },
    async keyWords(value) {
      if (value != '') {
        this.isipt = true;
        const {
          data: {
            result: { songs: res }
          }
        } = await this.$http.get(`/search?keywords= ${value}`);

        this.searchList = res.map(val => {
          return (val.isSearch = true);
        });
      } else {
        this.isipt = false;
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    //进入路由的时候，绑定滚动事件.
    next(vm => {
      window.addEventListener('scroll', vm.loadMore);
      window.addEventListener('scroll', vm.loadMore2);
    });
  },
  beforeRouteLeave(to, from, next) {
    window.removeEventListener('scroll', this.loadMore); //离开当前路由移除scroll事件
    window.removeEventListener('scroll', this.loadMore2); //离开当前路由移除scroll事件
    next();
  },
  computed: {
    addPage() {
      //计算属性依赖于 page  和 hotSong
      return this.keywordsList.slice(0, this.pageSize * this.page);
    },
    addPage2() {
      //计算属性依赖于 page  和 hotSong
      return this.searchList.slice(0, this.pageSize * this.page);
    }
  },
  methods: {
    clearHistory() {
      sessionStorage.clear();
      this.session = '';
    },
    jumpSongs1(ids) {
      let currentSongIndex = this.searchList.findIndex(val => {
        return val.id == ids;
      });
      let newSearchList = this.searchList.map((val, index) => {
        val.song = {
          alias: val.alias,
          artists: [{ name: val.name }]
        };
      });
      let currentObj = { currentSongIndex: currentSongIndex, newAllList: this.searchList };
      //显示播放器
      this.$store.commit('showPlayBox', true);
      this.$store.commit('setSongsObject', currentObj);
    },
    jumpSongs(ids) {
      let currentSongIndex = this.keywordsList.findIndex(val => {
        return val.id == ids;
      });
      let currentObj = { currentSongIndex: currentSongIndex, newAllList: this.keywordsList };
      //显示播放器
      this.$store.commit('showPlayBox', true);
      this.$store.commit('setSongsObject', currentObj);
    },
    searching() {
      this.isopen2 = true;
    },
    // musicList 加载
    loadMore() {
      let el = document.documentElement || document.body;
      let top = el.scrollTop + el.clientHeight;
      let moretop = this.$refs.more.offsetTop;
      var that = this;
      setTimeout(function () {
        if (top >= moretop + 40) {
          if (that.page >= that.keywordsList.length / that.pageSize) {
            return;
          }
          // this.showSong.length=0;
          that.page++; //下一页
          that.smallkeywordsList = that.keywordsList.slice(0, that.pageSize * that.page);
        }
      }, 1000);
      // if (this.page >= this.newAllList.length / this.pageSize) {
      //   alert('没有更多了');
      //   return;
      // }
      // // this.showSong.length=0;
      // this.page++; //下一页
      // this.newList = this.newAllList.slice(0, this.pageSize * this.page);
    },
    loadMore2() {
      let el = document.documentElement || document.body;
      let top = el.scrollTop + el.clientHeight;
      let moretop = this.$refs.more2.offsetTop;
      var that = this;
      setTimeout(function () {
        if (top >= moretop + 40 && !that.isopen2) {
          if (that.page2 >= that.searchList.length / that.pageSize2) {
            return;
          }
          // this.showSong.length=0;
          that.page2++; //下一页
          that.smallkeySearchList = that.searchList.slice(0, that.pageSize2 * that.page2);
        }
      }, 1000);
      // if (this.page >= this.newAllList.length / this.pageSize) {
      //   alert('没有更多了');
      //   return;
      // }
      // // this.showSong.length=0;
      // this.page++; //下一页
      // this.newList = this.newAllList.slice(0, this.pageSize * this.page);
    },

    focusing() {
      if (this.isopen2) {
        this.isopen2 = false;
        this.isopen = true;
        this.isUpdate = true;
        this.$refs.more.style.display = 'none';
      }
    },
    //清空输入框
    clearInput() {
      this.keyWords = '';
      this.isopen = true;
      this.isopen2 = false;
      this.keywordsList = [];
    },
    //关键词搜索
    async historyClcik(name) {
      let nameArray = [];
      if (sessionStorage.getItem('nameArray')) {
        nameArray = JSON.parse(sessionStorage.getItem('nameArray'));
        if (
          nameArray.every(val => {
            return val.name != name;
          })
        ) {
          nameArray.push({ name: name });
        }
        sessionStorage.setItem('nameArray', JSON.stringify(nameArray));
      } else {
        sessionStorage.setItem('nameArray', JSON.stringify([{ name: name }]));
      }
      this.session = JSON.parse(sessionStorage.getItem('nameArray'));
      const { data: re } = await this.$http.get(`/cloudsearch?keywords=${name}&limit=30&offset=30`);
      //song歌曲 artists 艺术家 歌手 album 专辑 name名称 歌名 作者名 专辑名
      if (re && re.result.songCount < 1) {
        this.searchList = false;
        return;
      }
      let list = re.result.songs.map(item => {
        item.song = {
          artists: [item.ar[0]],
          name: item.name,
          album: item.al,
          privilege: item.privilege
        };
        return item;
      });
      this.isopen = false;
      this.isopen2 = true;
      this.keywordsList = list;
      this.smallkeywordsList = this.keywordsList.slice(0, this.pageSize * this.page);
      this.keyWords = name;
    },
    //input搜索
    getSearchValue: _.debounce(async function () {
      if (this.keyWords != '') {
        const {
          data: {
            result: { songs: res }
          }
        } = await this.$http.get(`/search?keywords= ${this.keyWords}`);
        this.searchList = res;
        this.isUpdate = true;
      }
    }, 200),
    async getSearchHistory() {
      const {
        data: {
          result: { hots: res }
        }
      } = await this.$http.get('/search/hot');
      // this.$store.commit('setSearchList', res);
      this.historyList = res;
    },
    delSession(name) {
      const oldArray = JSON.parse(sessionStorage.getItem('nameArray'));
      const newArray = oldArray.filter(value => {
        return value.name != name;
      });
      sessionStorage.setItem('nameArray', JSON.stringify(newArray));
      this.session = newArray;
    }
  }
};
</script>
<style scoped lang="less">
.sl {
  padding: 0 10px;
}
.clearHistory {
  color: gray;
  border-bottom: 1px solid rgb(194, 186, 186);
  padding: 10px;
  text-align: center;
}
.search {
  min-height: 848px;
  padding-bottom: 70px;
}

.SearchListTitle {
  color: rgb(100, 135, 176);
  padding: 20px 0;
  padding-left: 45px;
  padding-top: 0;
  border-bottom: 2px solid rgb(227, 227, 227);
  box-shadow: gray;
}
.session_box {
  display: flex;
  flex-direction: column;
}
.searchInput {
  margin-bottom: 15px;
}
.close_btn {
  width: 16px;
  height: 16px;
  display: block;
  position: absolute;
  top: 4px;
  right: 7px;
  background: url()
    no-repeat;
  background-size: contain;
}
.iconFont {
  width: 13px;
  height: 13px;
  position: absolute;
  left: 0;
  top: 9px !important;
  margin: 0 9px;
  background: url()
    no-repeat;
  background-size: 13px;
}
.searchInput {
  box-sizing: border-box;
  width: 100%;
  padding: 15px 10px;
  position: relative;
  &::after {
    content: '';
    display: block;
    box-shadow: 1px 1px 1px #ccc;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 1px;
  }
}
.ipt {
  background-color: rgb(235, 236, 236);
  border-radius: 15px 15px;
  padding: 0 30px;
  position: relative;
}
.input-test {
  width: 100%;
  border: 1px solid transparent;
  background-color: rgb(235, 236, 236);
  outline: none;
  height: 25px;
  &::placeholder {
    //通过这个设置
    color: rgb(203, 201, 201) !important;
  }
}

.history_list {
  display: flex;
  flex-wrap: wrap;
  justify-content: start;
}
.history_container {
  padding-left: 12px;
  padding-right: 30px;
}
.more {
  text-align: center;
  line-height: 40px;
  font-size: 13px;
  color: #666;
}
.iconFont2 {
  width: 13px;
  height: 13px;
  position: absolute;
  left: 0;
  top: 20px !important;
  margin: 0 9px;
  background: url()
    no-repeat;
  background-size: 13px;
}
.icon1 {
  width: 15px;
  height: 15px;
  position: absolute;
  left: 0;
  top: 20px;
  background: url()
    no-repeat;
  background-size: 13px;
}
.icon2 {
  width: 15px;
  height: 15px;
  position: absolute;
  right: 0;
  top: 20px;
  background: url()
    no-repeat;
  background-size: 13px;
}
</style>